package com.gzu.finalwork.user.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import java.util.List;
@Slf4j
@Service
@RequiredArgsConstructor
public class AmapService {

    private final WebClient.Builder webClientBuilder;
    private final ObjectMapper objectMapper;

    @Value("${amap.api.key}")
    private String apiKey;

    @Value("${amap.api.base-url}")
    private String baseUrl;

    /**
     * 地理编码 - 地址转坐标
     */
    public List<String> geocode(String address) {
        try {
            WebClient webClient = webClientBuilder.baseUrl(baseUrl).build();

            String response = webClient.get()
                    .uri(uriBuilder -> uriBuilder
                            .path("/v3/geocode/geo")
                            .queryParam("key", apiKey)
                            .queryParam("address", address)
                            .build())
                    .retrieve()
                    .bodyToMono(String.class)
                    .block();

            System.out.println("高德API原始响应：" + response); // 添加调试日志
            
            JsonNode jsonNode = objectMapper.readTree(response);
            String status = jsonNode.get("status").asText();
            
            if ("1".equals(status)) {
                JsonNode geocodes = jsonNode.get("geocodes");
                if (geocodes.isArray() && geocodes.size() > 0) {
                    String location = geocodes.get(0).get("location").asText();
                    System.out.println("解析出的坐标：" + location); // 添加调试日志
                    
                    if (location != null && !location.isEmpty() && location.contains(",")) {
                        return List.of(location.split(","));
                    } else {
                        log.warn("坐标格式异常：{}", location);
                    }
                } else {
                    log.warn("地理编码无结果：{}", address);
                }
            } else {
                String info = jsonNode.has("info") ? jsonNode.get("info").asText() : "未知错误";
                log.error("地理编码API错误: status={}, info={}, address={}", status, info, address);
            }
        } catch (Exception e) {
            log.error("地理编码请求异常: address={}", address, e);
        }
        return null;
    }

    /**
     * 逆地理编码 - 坐标转地址
     */
    public String regeocode(double longitude, double latitude) {
        try {
            WebClient webClient = webClientBuilder.baseUrl(baseUrl).build();

            String location = longitude + "," + latitude;
            String response = webClient.get()
                    .uri(uriBuilder -> uriBuilder
                            .path("/v3/geocode/regeo")
                            .queryParam("key", apiKey)
                            .queryParam("location", location)
                            .build())
                    .retrieve()
                    .bodyToMono(String.class)
                    .block();

            JsonNode jsonNode = objectMapper.readTree(response);
            if ("1".equals(jsonNode.get("status").asText())) {
                return jsonNode.get("regeocode").get("formatted_address").asText();
            }
        } catch (Exception e) {
            log.error("逆地理编码失败: {},{}", longitude, latitude, e);
        }
        return null;
    }


    /**
     * 解析地理编码结果
     */
    public Double[] parseGeocodeResult(String geocodeResult) {
        try {
            JsonNode root = objectMapper.readTree(geocodeResult);
            JsonNode geocodes = root.path("geocodes");
            if (geocodes.isArray() && geocodes.size() > 0) {
                String location = geocodes.get(0).path("location").asText();
                if (location != null && !location.isEmpty()) {
                    String[] coords = location.split(",");
                    if (coords.length == 2) {
                        return new Double[]{
                                Double.parseDouble(coords[0]), // 经度
                                Double.parseDouble(coords[1])  // 纬度
                        };
                    }
                }
            }
        } catch (Exception e) {
            log.error("解析地理编码结果失败", e);
        }
        return null;
    }

    /**
     * 解析逆地理编码结果
     */
    public String[] parseReverseGeocodeResult(String reverseGeocodeResult) {
        try {
            JsonNode root = objectMapper.readTree(reverseGeocodeResult);
            JsonNode regeocode = root.path("regeocode");
            if (!regeocode.isMissingNode()) {
                String formattedAddress = regeocode.path("formatted_address").asText();
                JsonNode addressComponent = regeocode.path("addressComponent");
                String city = addressComponent.path("city").asText();
                String province = addressComponent.path("province").asText();

                return new String[]{formattedAddress, city, province};
            }
        } catch (Exception e) {
            log.error("解析逆地理编码结果失败", e);
        }
        return null;
    }

}